module.exports = class extends baseLogic {
    constructor() {
        super();
    }

    static init() {
        return new this();
    }

    /**
     * 根据ID获取分类
     * @param ID
     * @returns {Promise<Model>}
     */
    async getItemByID(ID) {
        return await this.DB.cms_article_label.Access.findById(ID);
    }

    /**
     * 根据Code获取分类
     * @param partnersId 企业ID (因为多个企业的分类编码无法控制重复，所以需增加企业ID参数，平台的企业ID为-1)
     * @param code 编码
     * @returns {Promise<Model>}
     */
    async getItemByCode(partnersId, code) {
        return await this.DB.cms_article_label.Access.findOne({
            where: {
                al_code: code,
                al_partners_id: partnersId
            },
            raw: true
        });
    }

    async getItems(queryModel) {
        let queryFilter = {
            al_del_flag: 0
        };
        let OP = this.DB.base.sequelize.Op;

        if (queryModel.partnersId) {
            queryFilter.al_partners_id = queryModel.partnersId;
        }

        if (queryModel.orgId) {
            queryFilter.al_org_id = queryModel.orgId;
        }

        if (queryModel.parentId) {
            queryFilter.al_parent_id = queryModel.parentId;
        }
        if (queryModel.parentIds) {
            queryFilter.al_parent_ids = {
                [OP.like]: `${queryModel.parentIds}%`
            }
        }

        if (!isNaN(queryModel.isWrite)) {
            queryFilter.al_is_write = queryModel.isWrite;
        }

        if (queryModel.type && queryModel.type !== '') {
            queryFilter.al_type = queryModel.type;
        }

        let ret = await this.DB.cms_article_label.Access.findAll({
            where: queryFilter,
            order: [
                ['al_sort', 'ASC']
            ],
            raw: true
        });

        return ret;
    }

    /**
     *根据可见程度获取记录
     * @param partnersId
     * @returns {Promise<Array<Model>>}
     */
    async getItemsByDegree(moduleId, userInfo) {
        let FindFilter = await this.func.degree.getDegree(moduleId, userInfo, {
            createBy: 'al_create_by',
            orgId: 'al_org_id',
            partnersId: 'al_partners_id'
        });
        let OP = this.DB.base.sequelize.Op;
        let ret = await this.DB.cms_article_label.Access.findAll({
            where: {
                al_is_write: 1,
                [OP.or]: [FindFilter, {
                    al_type: ['001', '003']
                }]
            },
            order: [
                ['al_sort', 'ASC']
            ],
            raw: true
        });

        return ret;
    }

    async GetTreeData(ParentID, Items) {
        let data = [];
        let getChildrens = function (pid) {
            let cdata = [];
            for (let i = 0; i < Items.length; i++) {
                let item = Items[i];
                if (item.al_parent_id === pid) {
                    let data_item = {
                        title: item.al_name,
                        value: item.al_id,
                        code: item.al_code,
                        key: item.al_id,
                        children: getChildrens(item.al_id)
                    };
                    if (data_item.children.length === 0) delete data_item.children;
                    cdata.push(data_item);
                }
            }
            return cdata;
        };
        if (ParentID > 0) {
            let curP = await this.DB.cms_article_label.Access.findOne({
                al_id: ParentID,
                raw: true
            });
            data.push({
                title: curP.al_name,
                value: curP.al_id,
                key: curP.al_id,
                code: item.al_code,
                children: getChildrens(curP.al_id)
            });
        } else {
            data = getChildrens(0);
        }
        return data;

    };

    async insertOrUpdate(data, user) {

        let Model = {};
        let al_id = data.ID ? data.ID : 0;
        let al_parent_id = data.ParentID ? data.ParentID : 0;
        if (al_id > 0) {
            Model = await this.DB.cms_article_label.Access.findById(al_id);
            if (!Model) {
                return null;
            }
            Model = Model.dataValues;
        } else {
            let MaxSort = await this.DB.cms_article_label.Access.max("al_sort", {
                where: {
                    al_parent_id: al_parent_id
                }
            });
            if (isNaN(MaxSort)) {
                MaxSort = 0;
            }
            //Model.zd_ID=0;
            Model.al_isparent = 0;
            Model.al_parent_id = al_parent_id;
            Model.al_sort = Number("0" + MaxSort) + 1;
            Model.al_create_date = moment().format("YYYY-MM-DD HH:mm:ss");
            Model.al_create_by = user.UserID;
        }
        Model.al_code = data.Code;
        Model.al_parent_ids = data.ParentIds + ',';
        Model.al_name = data.Name;
        Model.al_type = data.AlType;
        Model.al_other_attr = data.Attr;
        Model.al_partners_id = data.al_partners_id;
        Model.al_org_id = data.OrgID;
        Model.al_is_write = data.IsWrite ? 1 : 0;
        Model.al_description = data.Description;
        if (al_id > 0) {
            await this.DB.cms_article_label.Access.update(Model, {
                where: {
                    al_id: al_id
                }
            });
        } else {
            Model = await this.DB.cms_article_label.Access.create(Model);
        }
        await this.CheckIsParent(Model.al_id);
        return Model;
    }

    /**
     * 删除
     * @param {*} CurNodeParentID 当前节点的父级ID
     * @param {*} AllIDs_Array 待删除的节点ID数组
     */
    async delModule(CurNodeParentID, AllIDs_Array) {
        for (let i = 0; i < AllIDs_Array.length; i++) {
            let id = Number("0" + AllIDs_Array[i]);
            if (id > 0) {
                await this.DB.cms_article_label.Access.destroy({
                    where: {
                        al_id: id
                    }
                });
            }
        }
        await this.CheckIsParent(CurNodeParentID);
        return true;
    }

    async moveNode(queryModel) {
        if (queryModel.CurNodeID > 0) {
            await this.DB.cms_article_label.Access.update({
                al_parent_id: queryModel.TargetParentID,
                al_parent_ids: queryModel.parentIds + ',',
            }, {
                where: {
                    al_id: queryModel.CurNodeID
                }
            });
        }


        for (let i = 0; i < queryModel.TargetNodeChildrensIDs_array.length; i++) {
            let id = queryModel.TargetNodeChildrensIDs_array[i];
            await this.DB.cms_article_label.Access.update({
                al_sort: i
            }, {
                where: {
                    al_id: id
                }
            });
        }



        await this.CheckIsParent(queryModel.TargetParentID);
        await this.CheckIsParent(queryModel.old_parent);
        let curNode = await this.DB.cms_article_label.Access.findById(queryModel.CurNodeID);
        await this.updateParentsId(curNode);
        return true;

    }

    //更新字段 parent_ids
    async updateParentsId(parentObj) {
        if (parentObj.al_isparent) {
            let children = await this.DB.cms_article_label.Access.findAll({
                where: {
                    al_parent_id: parentObj.al_id
                },
                raw: true
            });
            if (children.length > 0) {
                children.forEach(async item => {
                    item.al_parent_ids = parentObj.al_parent_ids + parentObj.al_id + ',';
                    await this.DB.cms_article_label.Access.update({
                        al_parent_ids: item.al_parent_ids
                    }, {
                        where: {
                            al_id: item.al_id
                        }
                    });
                    await this.updateParentsId(item);
                })
            }
        }
    };

    // async asycDict(){
    //     let ret = await this.func.cmsArticleLabel.sync();
    //     return ret;
    // }

    async getDictsTreeData(queryModel) {
        let treeData = await this.func.partnersDict.GetTreeData(queryModel.partnersId, queryModel.label, queryModel.parentId);
        return treeData;
    }

    /**
     *
     * 检测是否是父级
     * @param {*} ParentID
     */
    async CheckIsParent(ParentID) {
        if (ParentID === 0) {
            return false;
        };
        let count = await this.DB.cms_article_label.Access.count({
            where: {
                al_parent_id: ParentID
            }

        });
        if (count === 0) {
            await this.DB.cms_article_label.Access.update({
                al_isparent: 0
            }, {
                where: {
                    al_id: ParentID
                }
            });
        } else {
            await this.DB.cms_article_label.Access.update({
                al_isparent: 1
            }, {
                where: {
                    al_id: ParentID
                }
            });
        }
        return true;

    }
};